package com.util;

import com.alibaba.druid.pool.DruidDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;

/*
    封装Druid数据库连接池的工具类
 */
public class DBUtils {
    private static DruidDataSource ds = null;

    static {
        try {
            ResourceBundle rb = ResourceBundle.getBundle("jdbc");
            //配置连接数据库的四大基本特征
            ds = new DruidDataSource();
            ds.setDriverClassName(rb.getString("driver"));
            ds.setUrl(rb.getString("url"));
            ds.setUsername(rb.getString("username"));
            ds.setPassword(rb.getString("pwd"));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private DBUtils() {
    }

    //数据源
    public static DataSource getDataSource() {
        return ds;
    }

    //获取连接
    public static Connection getConn() {
        try {
            return ds.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException("数据库连接失败!");
        }
    }

    //释放资源
    public static void close(Connection conn, ResultSet rs) {
        try {
            if (conn != null) {
                conn.close();
            }
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(Connection conn) {
        close(conn, null);
    }
}
